<template>
  <div>
      <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 alertj警示 cascader级联选择框-->
    <el-card>
        <el-alert title="警告提示的文案" type="warning" show-icon :closable="false"></el-alert>
        <el-row class="qwe">
        <el-col>
            <span>选择商品分类：</span>
            <el-cascader v-model="selectedParamsKeys" :options="cateList" :props="cateProps" @change="selectHandleChange"></el-cascader>
        </el-col>        
        </el-row>
        <el-tabs v-model="activeName" @tab-click="paramsHandleClick">
            <!-- 动态 -->
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" size="mini" :disabled="isBtn" @click="showDiolo">添加参数</el-button>
                <!-- 动态属性参数表格 -->
                <el-table :data="manyTableData" border stripe>
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <!-- 循环渲染出每个attr_vals 并且有自定义tag -->
                            <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作"><template  slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteEditDialog(scope.row.attr_id)">删除</el-button>                                                 
                    </template></el-table-column>
                </el-table>
            </el-tab-pane>

            <!-- 静态 -->
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" size="mini" :disabled="isBtn" @click="showDiolo">添加参数</el-button>
                <!-- 静态属性参数表格 -->
                <el-table :data="onlyTableData" border stripe>
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <!-- 循环渲染出每个attr_vals 并且有自定义tag -->
                            <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作"><template  slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteEditDialog(scope.row.attr_id)">删除</el-button>                                                 
                    </template></el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加'+isMany" :visible.sync="ParamsdialogVisible" width="50%" @close="addParamsDialogClosed">
        <el-form ref="addParmsFormRef" :model="addParmsForm" :rules="addParmsFormRules" label-width="100px">
            <el-form-item :label="isMany" prop="attr_name">
            <el-input v-model="addParmsForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="ParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitParams">确 定</el-button>
        </span>
    </el-dialog>

    <!--编辑对话框 -->
    <el-dialog :title="'修改'+isMany" :visible.sync="EditParamsdialogVisible" width="50%" @close="EditParamsDialogClosed">
        <el-form ref="EditParmsFormRef" :model="EditParmsForm" :rules="EditParmsFormRules" label-width="100px">
            <el-form-item :label="isMany" prop="attr_name">
            <el-input v-model="EditParmsForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="EditParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditCommitParams">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
    data() {
        return {
            cateList:[],  //下拉框那块的商品分列列表
            cateProps:{   //级联选择框的配置对象
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            selectedParamsKeys:[],  //级联选择框双向绑定
            activeName:'many',      //被激活的页签的名称

            manyTableData:[],      //动态参数的数据
            onlyTableData:[],      //静态参数的数据

            ParamsdialogVisible:false, //控制添加属性对话框

            addParmsForm:{  //添加参数的表单数据对象
                attr_name:'',
            },          
            addParmsFormRules:{     //添加表单验证规则对象
                attr_name:[{required:true,message:'请输入参数名称',trigger:'blur'}],
            },

            EditParamsdialogVisible:false,  //控制编辑对话框的显示与隐藏
            EditParmsForm:{attr_name:'',attr_id:''},        //编辑的表单数据
            EditParmsFormRules:{       //编辑表单验证规则
                attr_name:[{required:true,message:'请输入参数名称',trigger:'blur'}],
            },
            /*inputVisible:false,  //控制自定义attr_vals输入框
            inputValue:''        //双向绑定控制自定义attr_vals输入框的内容   */
        }
    },
    created() {
        this.getCateList()
    },
    methods: {
        //获取所有的商品分类
        async getCateList(){
            const {data:res}=await this.$http.get('categories')
            if(res.meta.status!==200){
            this.$message.error('获取商品分类失败')
            }
            this.cateList=res.data
            console.log('获取所有商品分类',res.data)
        },
        //级联选择框中项变化，会触发这个函数
        async selectHandleChange(){
            if(this.selectedParamsKeys.length!==3){
                this.selectedParamsKeys=[]
                this.manyTableData=[]
                this.onlyTableData=[]
                return
            }
            console.log('级联选择框',this.selectedParamsKeys)
            //根据所选的id和当前所处的面板，获取对应的参数
            const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel: this.activeName}})
            if(res.meta.status!==200){
            this.$message.error('获取参数列表失败')
            }
            console.log('获取参数列表',res.data) 

            res.data.forEach(item => {
                item.attr_vals=item.attr_vals?
                item.attr_vals.split(' '):[]
                
                item.inputVisible=false  //控制文本框的显示与隐藏
                item.inputValue=''       //文本框中输入的值
                
            })
            console.log('获取参数列表attr_vals',res.data) 

            if(this.activeName==='many'){
                this.manyTableData=res.data
            }else{
                this.onlyTableData=res.data
            }
        },      
        //Tab页签点击事件的处理函数
        paramsHandleClick(){
            // console.log('Tab页签',this.activeName)
            this.selectHandleChange()
        },
        showDiolo(){
            this.ParamsdialogVisible=true
        },
        addParamsDialogClosed(){
            this.$refs.addParmsFormRef.resetFields()
        },
        //点击确认添加参数
        commitParams(){
            this.$refs.addParmsFormRef.validate(async valid=>{
                if(!valid) return
                const {data:res}=await this.$http.post(`categories/${this.cateId}/attributes`,{attr_name:this.addParmsForm.attr_name,attr_sel:this.activeName,})
                if(res.meta.status!==201){
                    return this.$message.error('添加参数失败！')
                }
                this.$message.success('添加参数成功！')
                this.ParamsdialogVisible=false
                this.selectHandleChange()               
                })              
        },
        //展示编辑对话框 
        async showEditDialog(attr_id){
            const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,{params:{attr_sel:this.activeName}})
            if(res.meta.status!==200){
            return this.$message.error('获取编辑对话框失败')
            }
            this.EditParmsForm=res.data
            this.EditParamsdialogVisible=true
        },
        
        EditParamsDialogClosed(){ //清空编辑对话框，重置
            this.$refs.EditParmsFormRef.resetFields()
        },
        //编辑对话框的确认
        EditCommitParams(){
            this.$refs.EditParmsFormRef.validate(async valid=>{
                if(!valid) return
                const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.EditParmsForm.attr_id}`,{attr_name:this.EditParmsForm.attr_name,attr_sel:this.activeName})
                if(res.meta.status!==200){
                return this.$message.error('获取编辑对话框失败')
                }
                this.$message.success('修改对话框成功!')
                this.paramsHandleClick()
                this.EditParamsdialogVisible=false              
            })
        },
        //根据id删除
        async deleteEditDialog(attr_id){
        const confirmResult=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).catch(err=>err)
        // console.log('是否删除',confirmResult)  //cancel
        if(confirmResult!=='confirm'){
            return this.$message.info('已取消删除')
        }

        //删除逻辑
        const {data:res}=await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
        if(res.meta.status!==200){
            return this.$message.error('删除参数失败')
        }
        this.paramsHandleClick()
        },
        //控制自定义attr_vals输入框  按下Enter或失去焦点
        async handleInputConfirm(row){
            //判断attr_val输入框是否为空
            if(row.inputValue.trim().length===0){
                row.inputValue=''
                row.inputVisible=false
                return
            }
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue=''
            row.inputVisible=false

            //将新增的attr_vals通过请求发给后端的服务器
            const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{attr_name:row.attr_name, attr_sel:row.attr_sel, attr_vals:row.attr_vals.join(' '),})
            if(res.meta.status!==200){
            this.$message.error('修改参数项失败')
            }
            console.log('获取参数项列表',res.data)
            this.$message.success('添加参数项成功')

        },
        //展示输入框
        showInput(row){
            row.inputVisible=true            
            this.$nextTick(_ => {  //让文本自动获取焦点
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        //删除对应的参数可选项
        handleClose(index,row){
            row.attr_vals.splice(index,1)
            this.handleInputConfirm(row)
            this.$message.success('删除参数项成功！')
        }
        
    },
    computed:{
        // eslint-disable-next-line vue/return-in-computed-property
        //如果按钮需要被禁用，则返回true
        isBtn(){
            if(this.selectedParamsKeys.length!==3){
                return true
            }
            return false
        },
        //当前选中的三级id
        cateId(){
            if(this.selectedParamsKeys.length===3){
                return this.selectedParamsKeys[2]
            }
            return null
        },
        isMany(){
            if(this.activeName==='many'){
                return '动态参数'
            }else{
                return '静态参数'
            }
        }
    }
}

</script>

<style lang="less" scoped>
.qwe{
    margin:15px 0;
}
</style>